﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BL.Entity;
using BL.Service;
using System.Diagnostics;
using System.Security.Principal;
using System.Runtime.Remoting.Channels.Tcp;
using System.Collections;
using System.Runtime.Remoting.Channels;
using RemoteBase;
using System.Runtime.Remoting;
using System.Reflection;

namespace LTO
{
    /// <summary>
    /// Interaction logic for login.xaml
    /// </summary>
    public partial class login : Window
    {
        public bool IsMaster = false;
        public login()
        {
            InitializeComponent();
            txtUserName.Focus();


            string a = String.Format("Version: {0},Build Dated: {1}",
    System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(),
    System.IO.File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly().Location).ToShortDateString());
            this.Title = string.Format("Login :{0}", a);
        }
        public void CheckUserKickOf()
        {
            tbl_UserService userService = new tbl_UserService();
            do
            {
                User dto = userService.GetUser(Gobalsource.UserNameLogin);

                if (dto == null || dto.Active == false)
                {

                    this.Dispatcher.Invoke((Action)(() =>
                    {
                        Gobalsource.objChatWin.SendMessage("ถูกนำออกจากระบบ");
                        Process.GetCurrentProcess().Kill();
                    }));
                }
                System.Threading.Thread.Sleep(1000);
            } while (Gobalsource.IsAppRunning);

        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {

            Login();

        }

        private void Login()
        {
            Gobalsource.IsAppRunning = true;
            User login = new User()
            {
                UserName = txtUserName.Text,
                Password = txtPassword.Password
            };

            try
            {

                login = new tbl_UserService().Login(login);
                Gobalsource.UserIDLogin = login.UserID;
                Gobalsource.UserNameLogin = login.UserName;
                Gobalsource.IsOnlineMode = true;
                JoinToChatRoom();
                ClientMain mainApp = new ClientMain();
                mainApp.Show();

                System.Threading.Thread t = new System.Threading.Thread(CheckUserKickOf);
                t.Start();
                this.Hide();
            }
            catch (Exception ex)
            {
                Gobalsource.IsAppRunning = false;
                MessageBox.Show(ex.Message);
                Gobalsource.objChatWin = null;
                this.Dispatcher.InvokeShutdown();
            }

        }


        ArrayList alOnlineUser = new ArrayList();


        private void JoinToChatRoom()
        {
            string ServerUrl = System.Configuration.ConfigurationManager.AppSettings["ServerUrl"];


            if (Gobalsource.chan == null && Gobalsource.UserNameLogin.Trim().Length != 0)
            {
                Gobalsource.chan = new TcpChannel();
                ChannelServices.RegisterChannel(Gobalsource.chan, false);

                // Create an instance of the remote object


                Gobalsource.objChatWin.remoteObj = (SampleObject)Activator.GetObject(typeof(RemoteBase.SampleObject), string.Format("tcp://{0}:8080/ChatRoom", ServerUrl));


                try
                {
                    Gobalsource.objChatWin.remoteObj.LeaveChatRoom(Gobalsource.UserNameLogin);
                    if (!Gobalsource.objChatWin.remoteObj.JoinToChatRoom(Gobalsource.UserNameLogin))
                    {

                        MessageBox.Show(Gobalsource.UserNameLogin + " already joined, please try with different name");
                        ChannelServices.UnregisterChannel(Gobalsource.chan);
                        Gobalsource.chan = null;
                        Gobalsource.objChatWin.Close();

                        return;
                    }
                }
                catch (Exception)
                {

                    ChannelServices.UnregisterChannel(Gobalsource.chan);
                }

                Gobalsource.objChatWin.key = Gobalsource.objChatWin.remoteObj.CurrentKeyNo();

                Gobalsource.objChatWin.yourName = Gobalsource.UserNameLogin;


                if (IsMaster)
                {
                    Gobalsource.objChatWin.Show();
                }

            }
        }


        private void btnOffline_Click(object sender, RoutedEventArgs e)
        {
            Gobalsource.IsOnlineMode = false;
            Gobalsource.UserIDLogin = -99;
            Gobalsource.UserNameLogin = WindowsIdentity.GetCurrent().Name.ToString();
            new ClientMain().Show();
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Login();
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

    }
}
